<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

	/**
	* The attributes that are mass assignable.
	*
	* @var array
	*/
	protected $fillable = [
		'user_name', 'email', 'password',
	];

	/**
	 * 关联到模型的数据表
	 *
	 * @var string
	 */
	protected $table = 'dqm_user';

	/**
	 * The attributes that should be hidden for arrays.
	 *
	 * @var array
	 */
	protected $hidden = [
		'password', 'remember_token',
	];

	const FIELD_EMAIL = 'email';
	const FIELD_USER_NAME = 'user_name';
	const FIELD_PASSWORD = 'password';
	const FIELD_USER_STATUS = 'user_status';

	/**
	 * 用户状态: 1、可用 ; 0、禁用/鎖定
	 */
	const ENABLE_USER_STATUS = 1;
	const DISABLE_USER_STATUS = 0;

	/**
	 * @param array $data
	 * @return bool
	 */
	static public function add($data = array()){
		if(!empty($data)){
			$now = time();
			if(!isset($data['created_time'])){
				$data['created_time'] = $now;
			}
			if(!isset($data['updated_time'])) {
				$data['updated_time'] = $now;
			}
			$user_id = User::insertGetId($data);
			if($user_id){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}

	/**
	 * @param $email
	 * @return null
	 */
	static function get_user_by_email($email){
		if(!empty($email)){
			$condition['where'] = array(self::FIELD_EMAIL=>$email, self::FIELD_USER_STATUS=>self::ENABLE_USER_STATUS);
			$select['fields'] = array('salt_word', 'password');
			$result = User::select($select['fields'])->where($condition['where'])->first();
			if($result){
				return $result;
			}
		}
		return null;
	}


	/**
	 * 设置随机字符 椒盐值
	 *
	 * @param int $len
	 * @param null $chars
	 * @return string
	 */
	static public function set_salt($len = 6, $chars = null){
		if (is_null($chars)) {
			$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		}
		mt_srand(10000000*(double)microtime());
		for ($i = 0, $salt = '', $lc = strlen($chars)-1; $i < $len; $i++) {
			$salt .= $chars[mt_rand(0, $lc)];
		}
		return $salt;
	}

	/**
	 * 加密密码
	 *
	 * @param $password
	 * @param $salt
	 * @return string
	 */
	static public function encrypt_password($password, $salt){
		return md5(md5($password).$salt);
	}
}
